
#Finds files under directories given some criteria
module Loader
  class FileSeeker    
    attr_accessor :root, :match, :blacklist, :whitelist,
      :folder_blacklist, :folder_whitelist
    
    def initialize
      @match = /.+\.rb$/
      @root = ''
      @blacklist = MatchList.new
      @whitelist = MatchList.new
      @folder_blacklist = MatchList.new
      @folder_whitelist = MatchList.new
    end

    #def dir(whitelist_expr, blacklist_expr)
    
    def files_under_dir dir, match = nil
      #unless File.exist?(dir)
        dir = (@root + dir)
      #end
      _seek_dir(dir, match || @match)
    end
    
    private 
    
    def _seek_dir(dir, match)
      files = {}
      #puts "seek #{dir}"
      Dir.new(dir).each do |filename|
        next if filename[0,1] == '.'
        file = dir + '/' + filename
        if File.directory?(file)
          if !@folder_blacklist.matches(filename) || @folder_whitelist.matches(filename)            
            files.merge!(_seek_dir(file, match))
          end
        elsif filename =~ match
          next if @blacklist.matches(filename) && !@whitelist.matches(filename)
          files[filename] = file
        end
      end
      files
    end
  end
  
  class Seek < Magic::Singleton
    self.singleton_instance= FileSeeker.new
    
    #shorthand for files_under_dir
    def self.dir(dir, match = nil)
      self.files_under_dir(dir, match)
    end
  end
end